package com.thread;

import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

public class JUC_phaser_marrige_18 {

    static Phaser pharse = new marriage();

    static Random random = new Random();

    public static void main(String[] args) {

        pharse.bulkRegister(7);

        for(int i=0;i<5;i++){
            new Thread(new Person(i+"")).start();
        }
        new Thread(new Person("新郎")).start();
        new Thread(new Person("新娘")).start();

    }
    static  class  marriage extends Phaser{
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase){
                case 0://从0开始
                    System.out.println("人都到齐。。。。"+registeredParties);
                    System.out.println();
                    return false;
                case 1:
                    System.out.println("所有人都吃完。。。"+registeredParties);
                    System.out.println();
                    return false;
                case 2:
                    System.out.println("所有人都离开。。。"+registeredParties);
                    System.out.println();
                    return false;
                case 3:
                    System.out.println("婚礼结束。。。"+registeredParties);
                    System.out.println();
                    return true;
                default:
                    return true;
            }
        }
    }

    static class  Person extends Thread{
        String name;
        Person(String name){
            this.name = name;
        }

        void arrive(){
            try {
                TimeUnit.MILLISECONDS.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(this.name+"到达现场。。。");
            pharse.arriveAndAwaitAdvance();
        }
        void eat(){
            System.out.println(this.name+"到达开吃。。。");
            pharse.arriveAndAwaitAdvance();
        }
        void leave(){
            System.out.println(this.name+"离开现场。。。");
            pharse.arriveAndAwaitAdvance();
        }
        void hug(){
            if(this.name.equals("新郎")||this.name.equals("新娘")){
                System.out.println(this.name+"拥抱现场。。。");
                pharse.arriveAndAwaitAdvance();
            }else{
                pharse.arriveAndDeregister();
            }
        }
        @Override
        public void run() {
            arrive();
            eat();
            leave();
            hug();;
        }
    }
}
